<?php
/* ************************************************** *\
 * @company		: NovaITech							  *	
 * @author		: van.vo@novaitech.com				  * 
 * @copyright	: 2012								  * 
 * ================================================== *
 * @date		: {creation_date}
 * @project		: 
 * @description	: {description}
 *		- 
 *
\* ************************************************** */
class Customer extends MY_Controller {
    
    function __construct( ) {
        parent::__construct( );
		$this->load->library( array( 'form_validation', 'table' ) );		
		$this->load->helper( array( 'form', 'url' ) );
		$this->load->model( 'CodeGenerator_model', '', TRUE );
		$this->load_template();
	}	
	
	function index( ){
		$this->manage( );
	}

    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: View list
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function view( ){
        // Get rules from config file
        // --------------------------------------------------
	    //$rules                  =   $this->form_validation->_config_rules[ 'customer_add' ];
        $rules                  =   array(array('field_id' => 'Cust_ID','label' => 'Cust_ID','control' => 'Array',),array('field_id' => 'F_Name','label' => 'F_Name','control' => 'Array',),array('field_id' => 'L_Name','label' => 'L_Name','control' => 'Array',),array('field_id' => 'DOB','label' => 'DOB','control' => 'Array',),array('field_id' => 'Phone_NO','label' => 'Phone_NO','control' => 'Array',),array('field_id' => 'Street','label' => 'Street','control' => 'Array',),array('field_id' => 'District_City','label' => 'District_City','control' => 'Array',),array('field_id' => 'Membership_Type','label' => 'Membership_Type','control' => 'Array',),array('field_id' => 'Email_Addr','label' => 'Email_Addr','control' => 'Array',),array('field_id' => 'Create_Dt','label' => 'Create_Dt','control' => 'Array',),array('field_id' => 'Delete','label' => 'Delete','control' => 'Array',),);
	    $this->data[ 'rules' ]  =   $rules;
       
        // Make header
        // --------------------------------------------------
	    $header = array( );
	    foreach( $rules as $item ){
	        $header[ ] = $item[ 'label' ];
	    }
       
	    $this->data[ 'header' ] =   $header;
	    $results                =   $this->CodeGenerator_model->get( 'customer', 'Cust_ID,F_Name,L_Name,DOB,Phone_NO,Street,District_City,Membership_Type,Email_Addr,Create_Dt,Delete' );
	
        $actions  = array();
            
        
        
        // Make action Rent/Contact/Review
        // --------------------------------------------------
        for( $i = 0; $i < count( $results ); $i++ ){
            $id = array_values( $results[ $i ] );
            
            if(!empty($actions)){
                foreach ($actions as $item) {
                    $results[ $i ][ $item['action_name'] ]   = anchor( base_url( ) . 
                    'index.php/customer/'. $item['action_func'] . "/" . $id[ 0 ], $item['action_name']);
                }
            }
            
        }
        
        $this->data[ 'results'        ]   =   $results;
        $this->data[ 'master_limited' ]   =   explode(',', 'Cust_ID,F_Name,L_Name,DOB,Phone_NO,Street,District_City,Membership_Type,Email_Addr,Create_Dt,Delete');
        $this->data[ 'custom_action'  ]   =   $actions;
 
        $this->load->view( 'customer_list', $this->data ); 
    }
    
    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Manage list
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function manage( ){
		//paging
		$filter = $this->input->get('filter');
		$rdfilter=$rdfilter = $this->input->get('rdfilter');
		$txtsn = $this->input->get('txtsn');
		$txtinactive = $this->input->get('txtinactive');
		$post = false;
		if(empty($rdfilter)){
			$rdfilter = $this->input->post('rdfilter');
			$post = true;
		}
		$txtSearch = $this->input->get('txtSearch');
		if(empty($txtSearch))
			$txtSearch = $this->input->post('txtSearch');
		$str_search = "";
		if(!empty($txtSearch) && !is_numeric($txtSearch)) $str_search=" and (F_Name like '%$txtSearch%' or L_Name like '%$txtSearch%')";
		else $str_search=" and (Phone_NO like '$txtSearch%')";
		if(empty($txtsn))
			$txtsn = $this->input->post('txtsn');
		if(empty($txtinactive))
			$txtinactive = $this->input->post('txtinactive');	
		if(empty($rdfilter)) $rdfilter=3;
		if(empty($txtsn)) $txtsn=7;//7 ngay
		if(empty($txtinactive)) $txtinactive=3;//3 tuan
		
		$orderby = $this->input->get('orderby');
		$config['uri_segment'] = 3;
        $config['base_url'] = base_url().'customer/manage/';
		if($filter || $rdfilter) {$config['suffix'] = "/?filter=$filter&orderby=$orderby&rdfilter=$rdfilter&txtsn=$txtsn&txtinactive=$txtinactive&txtSearch=$txtSearch";
			$config['first_url'] = $config['base_url']."0/?filter=$filter&orderby=$orderby&rdfilter=$rdfilter&txtsn=$txtsn&txtinactive=$txtinactive&txtSearch=$txtSearch";
		}

        
		if(empty($filter)) $str_orderby = ''; else $str_orderby = "$filter $orderby";
        // Get rules from config file
        // --------------------------------------------------
        //$rules                  =   $this->form_validation->_config_rules[ 'customer_add' ];
        $rules                  =         array(
		array('field_id' => 'Full_Name','label' => 'Tên','control' => 'string','class'=>'first border-right','width'=>'10%','style'=>'border-right: solid 3px #fff;','class_child'=>'l'),
		// array('field_id' => 'L_Name','label' => 'Họ','control' => 'string','class'=>'border-right','width'=>'5%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'DOB','label' => 'Ngày sinh','control' => 'string','class'=>'border-right','width'=>'5%','style'=>'border-right: solid 3px #fff;','class_child'=>'c'),
		array('field_id' => 'Phone_NO','label' => 'Số ĐT','control' => 'string','class'=>'border-right','width'=>'5%','style'=>'border-right: solid 3px #fff;','class_child'=>'c'),
		// array('field_id' => 'Street','label' => 'Đường','control' => 'string','class'=>'border-right','width'=>'5%','style'=>'border-right: solid 3px #fff;'),
		// array('field_id' => 'District_City','label' => 'Tp','control' => 'string','class'=>'border-right','width'=>'5%','style'=>'border-right: solid 3px #fff;'),
		// array('field_id' => 'Membership_Type','label' => 'Loại thành viên','control' => 'string','class'=>'border-right','width'=>'5%','style'=>'border-right: solid 3px #fff;'),
		// array('field_id' => 'Email_Addr','label' => 'Email','control' => 'string','class'=>'border-right','width'=>'5%','style'=>'border-right: solid 3px #fff;'),
		// array('field_id' => 'Create_Dt','label' => 'Ngày tạo','control' => 'time','class'=>'border-right','width'=>'5%','style'=>'border-right: solid 3px #fff;')
		);
		
       
        $config['per_page'] = PER_PAGE;	
       
		$start = $this->uri->segment(3);
		if($post) {$start= 0;//neu la` post thi co' nghia la` phan trang se tro ve trang thai ban dau
			$config['uri_segment'] = 20;// dua page current ve 0
		}
		if(empty($start)) $start = 0;
		$perpage = $config['per_page'];
       
        // Make header
        // --------------------------------------------------
        $header = array( );
        foreach( $rules as $k => $item ){
             $header[ ] = $item[ 'label' ];
			$str1='';$str2='';
			if($filter == $item['field_id']){
				if($orderby == "DESC") {$orderby = "ASC";$img1="display: none;";$img2="display: inline;"; } else {$orderby = "DESC";$img1="display: inline;";$img2="display: none;";}
				$url= base_url()."customer/manage/$start/?filter=$filter&orderby=$orderby&rdfilter=$rdfilter&txtsn=$txtsn&txtinactive=$txtinactive&txtSearch=$txtSearch";
				$str1 = 'onmouseout="$(\'.soimg2\').toggle()" onmouseover="$(\'.soimg2\').toggle()"';
				$str2='<img class="icon ic_s_asc soimg2" alt="Ascending" title="" src="'.base_url().'resources/images/dot.gif" style="'.$img1.'"> <img class="icon ic_s_desc soimg2 hide" alt="Descending" title="" src="'.base_url().'resources/images/dot.gif" style="'.$img2.'">';
			}else $url= base_url()."customer/manage/$start/?filter=".$item['field_id']."&orderby=ASC&rdfilter=$rdfilter&txtsn=$txtsn&txtinactive=$txtinactive&txtSearch=$txtSearch";
			$rules[$k]['html'] ='<span><a title="" '.$str1.' href="'.$url.'">'.$item[ 'label' ].' '.$str2.'</a></span>';
			if(isset($item['order'])&&!$item['order']) $rules[$k]['html'] = $item[ 'label' ];
        }
		$this->data[ 'rules' ]  =   $rules;
	   
        $this->data[ 'header' ] =   $header;
		
		if($rdfilter==1){ // sinh nhat
			$day = $txtsn;
			$sql= "SELECT *,CONCAT(F_Name,' ',L_Name) as Full_Name, FLOOR( DATEDIFF( DATE( NOW( ) ) , STR_TO_DATE( DOB, '%d/%m/%Y' ) ) / 365.25 ) AS age_now, DATEDIFF(CONCAT(CONCAT(EXTRACT(YEAR FROM CURDATE()),'-'), DATE_FORMAT(STR_TO_DATE( DOB, '%d/%m/%Y' ), '%m-%d')), CURDATE()) AS birthdays
			FROM customer
			WHERE DATEDIFF(CONCAT(CONCAT(EXTRACT(YEAR FROM CURDATE()),'-'), DATE_FORMAT(STR_TO_DATE( DOB, '%d/%m/%Y' ), '%m-%d')), CURDATE()) <= $day and DATEDIFF(CONCAT(CONCAT(EXTRACT(YEAR FROM CURDATE()),'-'), DATE_FORMAT(STR_TO_DATE( DOB, '%d/%m/%Y' ), '%m-%d')), CURDATE()) >=0 $str_search $str_orderby Limit $start,$perpage";
			$results                =   $this->CodeGenerator_model->custom_query($sql,"array");
			$sql= "SELECT count(Cust_ID) as total
			FROM customer
			WHERE DATEDIFF(CONCAT(CONCAT(EXTRACT(YEAR FROM CURDATE()),'-'), DATE_FORMAT(STR_TO_DATE( DOB, '%d/%m/%Y' ), '%m-%d')), CURDATE()) <= $day and DATEDIFF(CONCAT(CONCAT(EXTRACT(YEAR FROM CURDATE()),'-'), DATE_FORMAT(STR_TO_DATE( DOB, '%d/%m/%Y' ), '%m-%d')), CURDATE()) >=0 $str_search";
			$total = $this->CodeGenerator_model->custom_query($sql,"array");
			$total_customer = $total[0]['total'];
		}else if($rdfilter==2){ //khach da lau ko den
			$limit['datemax']=time();
			$today = date("Y-m-d",time());
			$dateend = date('Y-m-d', strtotime("$today -$txtinactive weeks"));
			$limit['datemin'] = strtotime($dateend);
			$sql = "select *,CONCAT(F_Name,' ',L_Name) as Full_Name from customer where Cust_ID not in(Select t.Cust_ID from transaction as t where t.Create_Dt >= ".$limit['datemin']." AND t.Create_Dt <= ".$limit['datemax'].") $str_search $str_orderby Limit $start,$perpage";
			$results                =   $this->CodeGenerator_model->custom_query($sql,"array");
			$sql="select count(Cust_ID) as total from customer where Cust_ID not in(Select t.Cust_ID from transaction as t where t.Create_Dt >= ".$limit['datemin']." AND t.Create_Dt <= ".$limit['datemax'].") $str_search";
			$total = $this->CodeGenerator_model->custom_query($sql,"array");
			$total_customer = $total[0]['total'];
		}else{ //all
			$sql = "select *,CONCAT(F_Name,' ',L_Name) as Full_Name from customer where 1 $str_search $str_orderby Limit $start,$perpage";
			$results                =   $this->CodeGenerator_model->custom_query($sql,"array");  
			$sql="select count(Cust_ID) as total from customer where 1 $str_search";
			$total = $this->CodeGenerator_model->custom_query($sql,"array");
			$total_customer = $total[0]['total'];
			//$total_customer=$this->CodeGenerator_model->count("customer");
		}
		 $config['total_rows'] = $total_customer;
		 $this->pagination->initialize($config); 
       // $results                =   $this->CodeGenerator_model->get( 'customer', 'Cust_ID,F_Name,L_Name,DOB,Phone_NO,Street,District_City,Membership_Type,Email_Addr,Create_Dt,Delete','', $config['per_page'],$start,false,"array", $str_orderby );        
        
        // Make action Edit/Delete
        // --------------------------------------------------
        for( $i = 0; $i < count( $results ); $i++ ){
	       $id = array_values( $results[ $i ]);
            $results[ $i ][ 'Edit'   ]   =  anchor( base_url( ) . 'index.php/customer/edit/' . $id[ 0 ], 'Edit');  
            $results[ $i ][ 'Delete' ]   =  anchor( 
                        base_url( ) . 'index.php/customer/delete/' . $id[ 0 ], 
                        'Delete',
                        array( 'onClick' => 'return deletechecked(\' ' . base_url() . 'index.php/customer/delete/' . $id[ 0 ] . ' \')' ) );                        
        }
        
        $this->data[ 'results'        ]     =   $results;
        $this->data[ 'rdfilter'        ]     =   $rdfilter;
        $this->data[ 'txtsn'        ]     =   $txtsn;
        $this->data[ 'txtinactive'        ]     =   $txtinactive;
        $this->data[ 'master_limited' ]     =   explode(',', 'Cust_ID,F_Name,L_Name,Full_Name,DOB,Phone_NO,Street,District_City,Membership_Type,Email_Addr,Create_Dt,Delete');
        $this->data[ 'action'         ]     =   array(array('id' => 'new','label' => 'Thêm khách hàng','url' => 'index.php/customer/add/',),array('id' => 'edit','label' => 'Edit','url' => 'index.php/customer/edit/',),array('id' => 'delete','label' => 'Del','url' => '',),);
        // $this->load->view( 'customer_list', $this->data ); 
		$this->template->write( 'title', 'Spa - Danh sách khách hàng' );
        $this->template->write_view( 'content', 'customer_list.php',$this->data );
        $this->template->render();
    }
	

    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Load form add new record
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function add( ){            
		$this->data[ 'custom_error' ] = '';
		$username = "noname";
		$userid = 0;
		$Cust_ID = set_value('Cust_ID');
		if(!$Cust_ID)
			$Cust_ID="CC_".uniqid();
		$this->data['temp_id'] = $Cust_ID;
        if( $this->form_validation->run( 'customer_add' ) == false ){
             $this->data[ 'custom_error' ] = ( validation_errors( ) ? '<div class="form_error">' . validation_errors( ) . '</div>' : false );
        }else{    
			$this->form_validation->set_rules('Phone_NO', 'Phone_NO', 'callback_Phone_Number_check');
			if ($this->form_validation->run('customer_add') == false)
			{
				 $this->data['custom_error'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);
			}
			else{
				$data = array(
						'Cust_ID' =>$Cust_ID,
						'F_Name' => set_value('F_Name'),
						'L_Name' => set_value('L_Name'),
						'DOB' =>set_value('DOB'),
						'Phone_NO' => set_value('Phone_NO'),
						'Street' => set_value('Street'),
						'District_City' => set_value('District_City'),
						'Membership_Type' => set_value('Membership_Type'),
						'Email_Addr' => set_value('Email_Addr'),
						'Notes' => set_value('Notes'),
						'Create_Dt' => time()
				);
				$result = $this->CodeGenerator_model->add( 'customer', $data, 'Cust_ID' );
				if( $result == ADD_SUCCESSFULLY ){
					redirect( base_url() . 'index.php/customer/manage/' );
				}else if( $result == RECORD_EXISTED ){
					$this->data[ 'custom_error' ] = '<div class="form_error"><p>A record existed.</p></div>';
				}else{
					$this->data[ 'custom_error' ] = '<div class="form_error"><p>An Error Occured.</p></div>';
				}
			}
		}		   
		// $this->load->view( 'customer_add', $this->data );   
		$this->template->write( 'title', 'Spa - Tiếp nhận khách hàng' );
        $this->template->write_view( 'content', 'customer_add.php',$this->data );
        $this->template->render();
    }	

    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Load edit form.
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function edit( ){
        $this->data[ 'custom_error' ] = '';
		$username = "noname";
		$userid = 0;
        
        if( $this->form_validation->run( 'customer_edit' ) == false ){
            $this->data[ 'custom_error' ] = ( validation_errors( ) ? '<div class="form_error">' . validation_errors( ) . '</div>' : false );

        }else{ 
			$this->form_validation->set_rules('Phone_NO', 'Phone_NO', 'callback_Phone_Number_check');
			if ($this->form_validation->run('customer_edit') == false)
			{
				 $this->data['custom_error'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);
			}
			else{
				$data = array(
						'F_Name' => $this->input->post('F_Name'),
						'L_Name' => $this->input->post('L_Name'),
						'DOB' => $this->input->post('DOB'),
						'Phone_NO' => $this->input->post('Phone_NO'),
						'Street' => $this->input->post('Street'),
						'District_City' => $this->input->post('District_City'),
						'Membership_Type' => $this->input->post('Membership_Type'),
						'Email_Addr' => $this->input->post('Email_Addr'),
						'Notes' => $this->input->post('Notes'),
						'Create_Dt' => time()
				);
				if( $this->CodeGenerator_model->edit( 'customer', $data, 'Cust_ID', $this->input->post( 'Cust_ID' ) ) == TRUE ){
					redirect( base_url( ) . 'index.php/customer/manage/' );
				}else{
					$this->data[ 'custom_error' ] = '<div class="form_error"><p>An Error Occured</p></div>';
				}
			}
		}
		$this->data[ 'result' ]   =   $this->CodeGenerator_model->get( 'customer', 'Cust_ID,F_Name,L_Name,DOB,Phone_NO,Street,District_City,Membership_Type,Email_Addr,Create_Dt,Delete,Notes', 'Cust_ID = "' . $this->uri->segment( 3 ) . '"', NULL, NULL, true );  
		//get history
		$sql="select * from transaction where Cust_ID='".$this->uri->segment( 3 )."' order by create_dt desc limit 0,1";
		$history = $this->CodeGenerator_model->custom_query($sql,"array");
		if(!empty($history)){
			 //duyet service va nguoi duoc tip
				 $str_dv = "";
				 $str_nguoitip = "";
				 $Tran_ID = $history[0]['Tran_ID'];
			   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID,tt.Price  from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and e.EE_ID = tt.EE_ID and tt.Serv_ID = s.Serv_ID";
			   // echo $sql;die;
			   $services = $this->CodeGenerator_model->custom_query($sql,"array");
			 
			   foreach($services as $t){
					$str_dv .=$t['Serv_Name']."(".$t['Name'].")"." + ";
					$str_nguoitip .= $t['Personal_ID']."(".$t['Price']."k), ";
			   }  
			   
			   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID, p.TienTip,p.SoSuat, p.Conlai from services as s, categories as ca, employee as e, phieukh as p where p.Tran_ID='$Tran_ID' and p.EE_ID = e.EE_ID and s.Cat_ID = ca.Ca_ID and p.Serv_ID = s.Serv_ID";
			   $phieus = $this->CodeGenerator_model->custom_query($sql,"array");
			   foreach($phieus as $t){
					$str_dv .="Phieu ".$t['SoSuat']." suat - con lai ".$t['Conlai']." suat - ".$t['Serv_Name']."(".$t['Name'].")"." + ";
					$str_nguoitip .= $t['Personal_ID']."(".$t['TienTip']."k), ";
			   }
			   $Serv_FullName = substr($str_dv, 0, -3);
			   $EE_Name = substr($str_nguoitip,0,-2); 
		
		   $history[0]['Serv_FullName'] = $Serv_FullName;
		   $history[0]['EE_Name'] = $EE_Name;
		}
		
		
		
		$this->data['history']=$history;
		
		$this->load->view( 'customer_edit', $this->data );		
		$this->template->write( 'title', 'Spa - Thông tin khách hàng' );
        $this->template->write_view( 'content', 'customer_edit.php',$this->data );
        $this->template->render();
    }

    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Delete record
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function delete( ){
        $ID =  $this->uri->segment( 3 );
        $this->CodeGenerator_model->delete(  'customer', 'Cust_ID', $ID );             
        redirect( base_url( ) . 'index.php/customer/manage/' );
    } 

	function getmorehistory(){
		//get history
		$Cust_ID = $this->input->post("Cust_ID");
		$historypage = $this->input->post("historypage");
		$perpage= 1;
		$sql="select t.*,p.SoSuat, p.Conlai,p.Tang from transaction as t left join phieukh as p on t.Phieu_ID=p.ID where t.Cust_ID='$Cust_ID' order by create_dt desc limit $historypage,$perpage";
		// $data['sql'] = $sql;
		$history = $this->CodeGenerator_model->custom_query($sql,"array");
		$str_history = '';
		foreach($history as $k=>$item){
		   //duyet service va nguoi duoc tip
				 $str_dv = "";
				 $str_nguoitip = "";
				 $Tran_ID = $item['Tran_ID'];
			   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID,tt.Price  from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and e.EE_ID = tt.EE_ID and tt.Serv_ID = s.Serv_ID";
			   // echo $sql;die;
			   $services = $this->CodeGenerator_model->custom_query($sql,"array");
			 
			   foreach($services as $t){
					$str_dv .=$t['Serv_Name']."(".$t['Name'].")"." + ";
					$str_nguoitip .= $t['Personal_ID']."(".$t['Price']."k), ";
			   }  
			   
			   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID, p.TienTip,p.SoSuat, p.Conlai from services as s, categories as ca, employee as e, phieukh as p where p.Tran_ID='$Tran_ID' and p.EE_ID = e.EE_ID and s.Cat_ID = ca.Ca_ID and p.Serv_ID = s.Serv_ID";
			   $phieus = $this->CodeGenerator_model->custom_query($sql,"array");
			   foreach($phieus as $t){
					$str_dv .="Phieu ".$t['SoSuat']." suat - con lai ".$t['Conlai']." suat - ".$t['Serv_Name']."(".$t['Name'].")"." + ";
					$str_nguoitip .= $t['Personal_ID']."(".$t['TienTip']."k), ";
			   }
			   $Serv_FullName = substr($str_dv, 0, -3);
			   $EE_Name = substr($str_nguoitip,0,-2); 
		   $history[$k]['Serv_FullName'] =$Serv_FullName;
		   $history[$k]['EE_Name'] = $EE_Name;
		   $str_phieu = '';
				$str_history .='<p style="clear: both; margin: 10px; float: left; text-align: left;">+ '.date("d/m/Y",$history[$k]['Create_Dt']).' - dịch vụ: '.$history[$k]['Serv_FullName'].' - nguời típ: '.$history[$k]['EE_Name'].' - giá: '.formatcurrency($history[$k]['Price']*1000).' - giảm: '.$history[$k]['Discount_Percent'].'% - thành tiền: '.formatcurrency($history[$k]['Money']*1000).'</p>';
		}
		$data['html'] = $str_history;
		
		$data['historypage'] = $historypage + $perpage;
		echo json_encode($data);
		exit;
	}

	function search(){
		$term = $this->input->get('term');
		// $term = "test";
		
		$controler = $this->uri->segment( 1 );
		// $tmp = explode(", ",$term);
		// if(count($tmp)>0) $term = $tmp[count($tmp)-1];
		if(is_numeric($term))
			$where = "Phone_NO like '$term%'";
		else
			$where ="F_Name like '%$term%' or L_Name like '%$term%'";
		$sql = "select Cust_ID as id, CONCAT(F_Name, ' ' , L_Name, '( ',Phone_NO,'') as label, CONCAT(F_Name, ' ' , L_Name) as value from customer where $where";
		$results = $this->CodeGenerator_model->custom_query($sql, "array");
		//print_r($results);
		foreach($results as $k => $item){
			//get history
			$sql="select Serv_ID,Create_Dt,EE_Name,Tran_ID from transaction where Cust_ID='".$item['id']."' order by create_dt desc limit 0,1";
 
			$history = $this->CodeGenerator_model->custom_query($sql,"array");
			if(!empty($history)){
			    //duyet service va nguoi duoc tip
				 $str_dv = "";
				 $str_nguoitip = "";
				 $Tran_ID = $history[0]['Tran_ID'];
			   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID,tt.Price  from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and e.EE_ID = tt.EE_ID and tt.Serv_ID = s.Serv_ID and tt.Vip=0";
			   $services = $this->CodeGenerator_model->custom_query($sql,"array");
			
			   foreach($services as $t){
					$str_dv .=$t['Serv_Name']."(".$t['Name'].")"." + ";
					$str_nguoitip .= $t['Personal_ID']."(".$t['Price']."k), ";
			   }  
			   //phieu
			   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID, p.TienTip,p.SoSuat, p.Conlai from services as s, categories as ca, employee as e, phieukh as p where p.Tran_ID='$Tran_ID' and p.EE_ID = e.EE_ID and s.Cat_ID = ca.Ca_ID and p.Serv_ID = s.Serv_ID and p.Active=1";
			   $phieus = $this->CodeGenerator_model->custom_query($sql,"array");
			   foreach($phieus as $t){
					$str_dv .="Phieu ".$t['SoSuat']." suat - con lai ".$t['Conlai']." suat - ".$t['Serv_Name']."(".$t['Name'].")"." + ";
					$str_nguoitip .= $t['Personal_ID']."(".$t['TienTip']."k), ";
			   }
			    
			   //vip
				$sql = "select s.Serv_Name, ca.Name,tt.Price,tt.Price_Serv,tt.ID from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and tt.Serv_ID = s.Serv_ID and tt.Vip=1 Group by tt.ID";
	
			   $services_vip = $this->CodeGenerator_model->custom_query($sql,"array");
			   foreach($services_vip as $t){
					$str_dv .=$t['Serv_Name']."(".$t['Name'].")"." + ";
					$sql = "select e.Personal_ID, e.Name as e_Name,tv.Price,tv.Price_Serv from transaction_vip as tv, employee as e where e.EE_ID=tv.EE_ID and tv.TienTip_ID='".$t['ID']."'";
					$child=$this->CodeGenerator_model->custom_query($sql,"array");
					foreach($child as $l){
						$str_nguoitip .= $l['e_Name']."(".$l['Price']."k), ";
					}
					
			   }
			   
			   $Serv_FullName = substr($str_dv, 0, -3);
			   $EE_Name = substr($str_nguoitip,0,-2); 

				$results[$k]['label'] .=" - ". $Serv_FullName." - ".$EE_Name." - ".date("d/m/Y",$history[0]['Create_Dt']).")";
			}else{				
				 $results[$k]['label'] .=")";
			}
		}
		echo json_encode($results);
		exit();
	}
}